import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';

import { Storage } from './storage';
import {SERVER_PATH as ServerPath, TOKEN} from '../../app.config';
import'rxjs/add/operator/do';

@Injectable()
export class NoopInterceptor implements HttpInterceptor {
	constructor(
    private storage:Storage,
  ){
  }


  intercept(req:HttpRequest<any>, next:HttpHandler):Observable<HttpEvent<any>>{
  	const method = req.method;
    const body = req.body;
    const acctoken = this.storage.get(TOKEN);
  	const headers = {};
  	let url = ServerPath + req.url;

  	if(acctoken){
  		headers[TOKEN] = acctoken;
  	}

    if(method === 'GET' && body){
      url = url + '?' + this.formData(body);
    }

    const newReq = req.clone({
      url:url,
      setHeaders:headers
    });
    return next.handle(newReq);
  }



  private formData(data:Object){
    return Object.keys(data).map(function(key){
      return encodeURIComponent(key) + '=' + encodeURIComponent(data[key]);
    }).join('&');
  }



}